package com.babylove.project.product.service.impl;

import com.babylove.common.utils.DateUtils;
import com.babylove.common.utils.SecurityUtils;
import com.babylove.common.utils.StringUtils;
import com.babylove.project.product.domain.Store;
import com.babylove.project.product.domain.vo.StoreVo;
import com.babylove.project.product.mapper.StoreMapper;
import com.babylove.project.product.service.StoreService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: babylove
 * @BelongsPackage: com.babylove.project.product.service.impl
 * @Author: caoqingwen
 * @CreateTime: 2020-06-30 23:28
 * @Description: 仓库Service
 */
@Service
public class StoreServiceImpl implements StoreService {

    @Resource
    private StoreMapper storeMapper;

    /**
     * 查询仓库列表
     * @param req
     * @return
     */
    @Override
    public List<StoreVo> selectStoreList(StoreVo req) {
        return storeMapper.selectStoreList(req);
    }

    /**
     * 新增、修改仓库
     *
     * @param store
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveStore(Store store) {
        int row = 0;
        if (store.getId() == null) {
            String storeNum = getStoreNum();
            store.setStoreNum(storeNum);
            store.setCreateBy(SecurityUtils.getUsername());
            store.setCreateTime(new Date());
            row = storeMapper.insertStore(store);

        } else {
            store.setUpdateBy(SecurityUtils.getUsername());
            store.setUpdateTime(new Date());
            row = storeMapper.updateStore(store);
        }

        return row;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteStore(String id) {
        return storeMapper.deleteStore(id);
    }

    private String getStoreNum() {
        //格式CK-20200703001
        String storeNum = "CK-";
        String newDateStr = DateUtils.dateTime();
        String maxStoreNum = storeMapper.getMaxStoreNum();
        if (StringUtils.isNotEmpty(maxStoreNum)) {
            String oldDateStr = maxStoreNum.substring(3, 11);
            if (newDateStr.equals(oldDateStr)) {
                String oldNum = maxStoreNum.substring(11);
                Integer newNum = Integer.parseInt(oldNum) + 1;
                storeNum = storeNum + newDateStr + (String.format("%03d", newNum));
            } else {
                storeNum = storeNum + newDateStr + "001";
            }

        } else {
            storeNum = storeNum + newDateStr + "001";
        }
        return storeNum;


    }
}
